package com.wwp.tbshop.activity.category;

import android.content.Intent;
import android.graphics.Color;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.itheima.pulltorefreshlib.ILoadingLayout;
import com.itheima.pulltorefreshlib.PullToRefreshBase;
import com.itheima.pulltorefreshlib.PullToRefreshGridView;
import com.itheima.pulltorefreshlib.PullToRefreshListView;
import com.wwp.tbshop.R;
import com.wwp.tbshop.activity.BaseActivity;
import com.wwp.tbshop.activity.SearchActivity;
import com.wwp.tbshop.model.bean.CategoryInfo;
import com.wwp.tbshop.model.bean.FilterBean;
import com.wwp.tbshop.model.bean.GoodsListBean;
import com.wwp.tbshop.presenter.GoodsListPresenter;
import com.wwp.tbshop.view.adapter.FilterRvAdapter;
import com.wwp.tbshop.view.adapter.GoodsListGvAdapter;
import com.wwp.tbshop.view.adapter.GoodsListLvAdapter;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by 楠GG on 2017/6/17.
 */

public class GoodsListActivity extends BaseActivity {
    private static final String TAG = "GoodsListActivity";

    @Bind(R.id.back)
    ImageView mBack;
    @Bind(R.id.edit_text)
    EditText mEditText;
    @Bind(R.id.tv_price_up)
    TextView mTvPriceUp;
    @Bind(R.id.tv_sale_num)
    TextView mTvSaleNum;
    @Bind(R.id.iv_list)
    ImageView mIvList;
    @Bind(R.id.iv_grid)
    ImageView mIvGrid;
    @Bind(R.id.rl_list)
    RelativeLayout mRlList;
    @Bind(R.id.tv_filter)
    TextView mTvFilter;
    @Bind(R.id.rv)
    PullToRefreshListView mListView;
    @Bind(R.id.grid_view)
    PullToRefreshGridView mGridView;
    @Bind(R.id.fl_container)
    FrameLayout mFlContainer;
    @Bind(R.id.drawer)
    DrawerLayout mDrawer;
    @Bind(R.id.rl_empty)
    RelativeLayout mRlEmpty;

    private String mListName;
    public int mCId;
    private GoodsListLvAdapter mGoodsListLvAdapter;
    private GoodsListGvAdapter mGoodsListGvAdapter;
    private boolean isGridList = true;
    private static final int PAGE_NUM = 10;
    /**
     * 价格升序
     */
    public static final String PRICE_UP = "priceUp";
    /**
     * 销量降序
     */
    public static final String SALE_DOWN = "saleDown";
    public String typeOrder = SALE_DOWN;
    private boolean isFirstLoading = true;
    private GoodsListPresenter mGoodsListPresenter;
    private int mPage = 1;//默认进来第一页
    private int mListCount;
    private TableLayout mTlBrand;
    private TableLayout mTlPrice;
    private TableLayout mTlColor;
    private Button mBtnReset;
    private Button mBtnConfirm;
    private List<GoodsListBean.ProductListBean> mProductList = new ArrayList<>();
    private RecyclerView mFilterRv;
    private FilterRvAdapter mFilterRvAdapter;

    @Override
    public int getLayoutId() {
        return R.layout.activity_goods_list;
    }

    @Override
    protected void init() {
        super.init();
        processIntent();
        initFilterLayout();

        //设置listView
        mEditText.setText(mListName);
//        mListView.setLayoutManager(new LinearLayoutManager(this));
        mGoodsListLvAdapter = new GoodsListLvAdapter(this);
        mListView.setMode(PullToRefreshBase.Mode.BOTH);
        //处理下拉刷新的属性
        initListIndicator(mListView);

        mListView.setAdapter(mGoodsListLvAdapter);
        mListView.setOnRefreshListener(refreshListener1);

        //设置gridView
        mGoodsListGvAdapter = new GoodsListGvAdapter(this);
        mGridView.setMode(PullToRefreshBase.Mode.BOTH);
        initGridIndicator(mGridView);

        mGridView.setAdapter(mGoodsListGvAdapter);
        mGridView.setOnRefreshListener(refreshListener2);
//        mGoodsListGvAdapter = new GoodsListGvAdapter(this);
//        mGridView.setAdapter(mGoodsListGvAdapter);
        //从服务器拿数据
        mGoodsListPresenter = new GoodsListPresenter(this);

        mGoodsListPresenter.loadGoodsList(mPage, PAGE_NUM, mCId, "saleDown", "");

    }

    private void initGridIndicator(PullToRefreshGridView gridView) {
        ILoadingLayout startLabels = gridView
                .getLoadingLayoutProxy(true, false);
        startLabels.setPullLabel("你可劲拉，拉...");// 刚下拉时，显示的提示
        startLabels.setRefreshingLabel("好嘞，正在刷新...");// 刷新时
        startLabels.setReleaseLabel("你敢放，我就敢刷新...");// 下来达到一定距离时，显示的提示

        ILoadingLayout endLabels = gridView.getLoadingLayoutProxy(
                false, true);
        endLabels.setPullLabel("你可劲拉，拉...");// 刚下拉时，显示的提示
        endLabels.setRefreshingLabel("好嘞，正在加载...");// 刷新时
        endLabels.setReleaseLabel("你敢放，我就敢加载...");// 下来达到一定距离时，显示的提示
    }

    private void initListIndicator(PullToRefreshListView listView) {
        ILoadingLayout startLabels = listView
                .getLoadingLayoutProxy(true, false);
        startLabels.setPullLabel("你可劲拉，拉...");// 刚下拉时，显示的提示
        startLabels.setRefreshingLabel("好嘞，正在刷新...");// 刷新时
        startLabels.setReleaseLabel("你敢放，我就敢刷新...");// 下来达到一定距离时，显示的提示

        ILoadingLayout endLabels = listView.getLoadingLayoutProxy(
                false, true);
        endLabels.setPullLabel("你可劲拉，拉...");// 刚下拉时，显示的提示
        endLabels.setRefreshingLabel("好嘞，正在加载...");// 刷新时
        endLabels.setReleaseLabel("你敢放，我就敢加载...");// 下来达到一定距离时，显示的提示
    }

    private PullToRefreshBase.OnRefreshListener2<ListView> refreshListener1 = new PullToRefreshBase.OnRefreshListener2<ListView>() {
        @Override
        public void onPullDownToRefresh(PullToRefreshBase<ListView> pullToRefreshBase) {
            mListView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mPage = 1;
                    mProductList.clear();
                    mGoodsListPresenter.loadGoodsList(mPage, PAGE_NUM, mCId, typeOrder, "");
                    mListView.onRefreshComplete();
                }
            }, 1000);
        }

        @Override
        public void onPullUpToRefresh(PullToRefreshBase<ListView> pullToRefreshBase) {
            mListView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mPage++;
                    mGoodsListPresenter.loadGoodsList(mPage, PAGE_NUM, mCId, typeOrder, "");
                    mListView.onRefreshComplete();
                }
            }, 1000);
        }

    };

    private PullToRefreshBase.OnRefreshListener2<GridView> refreshListener2 = new PullToRefreshBase.OnRefreshListener2<GridView>() {
        @Override
        public void onPullDownToRefresh(PullToRefreshBase<GridView> pullToRefreshBase) {
            mGridView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mPage = 1;
                    mProductList.clear();
                    mGoodsListPresenter.loadGoodsList(mPage, PAGE_NUM, mCId, typeOrder, "");
                    mGridView.onRefreshComplete();
                }
            }, 1000);
        }

        @Override
        public void onPullUpToRefresh(PullToRefreshBase<GridView> pullToRefreshBase) {
            mGridView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mPage++;
                    mGoodsListPresenter.loadGoodsList(mPage, PAGE_NUM, mCId, typeOrder, "");
                    mGridView.onRefreshComplete();
                }
            }, 1000);
        }

    };

    private void initFilterLayout() {
        View view = LayoutInflater.from(this).inflate(R.layout.fragment_filter, null);

//        mTlBrand = (TableLayout) view.findViewById(R.id.tl_brand);
//        mTlPrice = (TableLayout) view.findViewById(R.id.tl_price);
//        mTlColor = (TableLayout) view.findViewById(R.id.tl_color);
        mFilterRv = (RecyclerView) view.findViewById(R.id.rv);

        mBtnReset = (Button) view.findViewById(R.id.btn_reset);
        mBtnConfirm = (Button) view.findViewById(R.id.btn_confirm);

        mFilterRv.setLayoutManager(new LinearLayoutManager(this));
        mFilterRvAdapter = new FilterRvAdapter(this);
        mFilterRv.setAdapter(mFilterRvAdapter);
        mFlContainer.addView(view);

        initFilterClick();
    }

    private void initFilterClick() {
        mDrawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
        mBtnReset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //重置
                mProductList.clear();
                mFilterRvAdapter.mIdList.clear();
                isFirstLoading = true;
                mGoodsListPresenter.loadGoodsList(1, PAGE_NUM, mCId, typeOrder, "");
            }
        });

        mBtnConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //确定
                mDrawer.closeDrawer(mFlContainer);
                List<String> idList = mFilterRvAdapter.mIdList;
                String filter = "";
                if(idList.size() != 0) {
                    for (int i = 0; i < idList.size(); i++) {
                        if(i == idList.size() - 1) {
                            filter += idList.get(i);
                        }else {
                            filter += idList.get(i) + "-";
                        }
                    }

                    mProductList.clear();

                }
                Toast.makeText(GoodsListActivity.this, filter, Toast.LENGTH_SHORT).show();
                mGoodsListPresenter.loadGoodsList(1, PAGE_NUM, mCId, typeOrder, filter);
            }
        });
    }

    private void initFilterData(TableLayout tableLayout,
                                List<GoodsListBean.ListFilterBean.ValueListBean> mDataList) {
        int count = mDataList.size();
        int raw;
        if (count % 3 == 0) {
            raw = count / 3;
        } else {
            raw = count / 3 + 1;
        }

        /**
         *   5        6
         * 0 1 2    0 1 2
         * 3 4      3 4 5
         **/

        int sum = 0;
        for (int i = 0; i < raw; i++) {
            TableRow tableRow = new TableRow(this);
            int col = count - 3 * i;
            if (col > 3) {
                col = 3;
            }
            for (int j = 0; j < col; j++) {
                TextView textView = new TextView(this);
                TableRow.LayoutParams params = new TableRow.LayoutParams();
                params.width = 150;
                params.height = 80;
                params.setMargins(10, 0, 0, 10);
                textView.setLayoutParams(params);

                textView.setGravity(Gravity.CENTER);
                textView.setText(mDataList.get(sum++).name);
                textView.setTextColor(Color.BLACK);
                textView.setTextSize(12);
                textView.setPadding(10, 10, 10, 10);
                textView.setBackgroundColor(Color.parseColor("#33000000"));
                tableRow.addView(textView);
            }
            tableLayout.addView(tableRow);
        }
    }

    private void processIntent() {
        if (getIntent() != null) {
            mListName = getIntent().getStringExtra("name");
            mCId = getIntent().getIntExtra("cId", 0);
        }
    }

    @OnClick({R.id.back, R.id.edit_text, R.id.tv_price_up, R.id.tv_sale_num,
            R.id.rl_list, R.id.tv_filter})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.edit_text:
                //跳转搜索界面
                Intent intent = new Intent(this, SearchActivity.class);
                intent.putExtra("name", mListName);
                startActivity(intent);
                break;
            case R.id.tv_price_up:
                //价格升序
                mTvPriceUp.setTextColor(Color.RED);
                mTvSaleNum.setTextColor(Color.GRAY);
                typeOrder = PRICE_UP;
                //重置页数
                mPage = 1;
                mListCount = -1;

                //请求获取数据
                mProductList.clear();
                mGoodsListPresenter.loadGoodsList(mPage, PAGE_NUM, mCId, typeOrder, "");

                break;
            case R.id.tv_sale_num:
                //销量降序
                mTvPriceUp.setTextColor(Color.GRAY);
                mTvSaleNum.setTextColor(Color.RED);
                typeOrder = SALE_DOWN;
                mPage = 1;
                mListCount = -1;

                //请求获取数据
                mProductList.clear();
                mGoodsListPresenter.loadGoodsList(mPage, PAGE_NUM, mCId, typeOrder, "");

                break;
            case R.id.rl_list:
                //切换recyclerView与GridView
                if (isGridList) {
                    //如果是list形式
                    mIvList.setImageResource(R.mipmap.list);
                    mListView.setVisibility(View.VISIBLE);
                    mGridView.setVisibility(View.GONE);
                } else {
                    mIvList.setImageResource(R.mipmap.grid);
                    mListView.setVisibility(View.GONE);
                    mGridView.setVisibility(View.VISIBLE);
                }
                isGridList = !isGridList;
                break;
            case R.id.tv_filter:
                //筛选
                mDrawer.openDrawer(mFlContainer, true);
                break;
        }
    }

    public void onServerBug(int code) {
        Toast.makeText(this, "网络繁忙", Toast.LENGTH_SHORT).show();
    }

    public void onError(String message) {
        Toast.makeText(this, "网络错误", Toast.LENGTH_SHORT).show();
    }

    public void onSuccess(GoodsListBean goodsListBean) {
        Log.d(TAG, "onSuccess: ");

        if(isFirstLoading) {
            List<GoodsListBean.ListFilterBean> listFilter = goodsListBean.listFilter;
            List<FilterBean> filterBeen = transfore(listFilter);

            mFilterRvAdapter.setDatas(filterBeen);
            isFirstLoading = false;
        }

        //设置数据
        List<GoodsListBean.ProductListBean> productList = goodsListBean.productList;

//        mGoodsListGvAdapter.setDatas(productList);
        mProductList.addAll(productList);
        if (mProductList.size() == 0) {
            mRlEmpty.setVisibility(View.VISIBLE);
        } else {
            mRlEmpty.setVisibility(View.GONE);
        }

        mGoodsListLvAdapter.setDatas(mProductList);
        mGoodsListGvAdapter.setDatas(mProductList);
    }

    private List<FilterBean> transfore(List<GoodsListBean.ListFilterBean> listFilter) {
        List<FilterBean> filterBeanList = new ArrayList<>();
        for (int i = 0; i < listFilter.size(); i++) {
            FilterBean titleBean = new FilterBean();
            titleBean.type = FilterBean.TYPE_TITLE;
            titleBean.title = listFilter.get(i).key;
            filterBeanList.add(titleBean);

            List<GoodsListBean.ListFilterBean.ValueListBean> valueList = listFilter.get(i).valueList;
            int count = 0;
            for (int j = 0; j < valueList.size() / 3; j++) {
                //三级标题3个，6个
                FilterBean info = new FilterBean();

                info.filterType = titleBean.title;
                info.type = CategoryInfo.TYPE_NORMAL;
                info.name1 = valueList.get(count * 3 + 0).name;
                info.name2 = valueList.get(count * 3 + 1).name;
                info.name3 = valueList.get(count * 3 + 2).name;

                info.id1 = valueList.get(count * 3 + 0).id;
                info.id2 = valueList.get(count * 3 + 1).id;
                info.id3 = valueList.get(count * 3 + 2).id;

                count++;
                filterBeanList.add(info);
            }
        }
        return filterBeanList;
    }
}
